/* eslint-disable promise/always-return */
/* eslint-disable no-use-before-define */
const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const ffmpeg = require('fluent-ffmpeg');

const app = express();
const port = 3000;

// 配置 multer 存储
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/'); // 上传目录
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + path.extname(file.originalname)); // 文件名
  },
});

const upload = multer({ storage });

// 确保 uploads 目录存在
if (!fs.existsSync('uploads')) {
  fs.mkdirSync('uploads');
}

app.post('/upload', upload.single('file'), (req, res) => {
  console.log('File uploaded:', req.file);

  res.send(
    JSON.stringify({
      tempFilePath: '11111',
    })
  );
});

// 上传文件的路由
app.post('/merge', upload.single('file'), (req, res) => {
  console.log('File uploaded:', req.file);

  // 处理上传的文件
  const filePath = req.file.path;
  const fileName = req.file.filename;

  // 保存文件路径用于后续处理
  // 这里假设你将所有视频片段保存在 uploads 目录中
  const segmentFilePath = path.join('uploads', fileName);
  const segmentFiles = [segmentFilePath]; // 你可以在这里收集多个视频片段路径

  // 合并视频
  mergeVideos(segmentFiles, 'uploads/final_output.mp4')
    .then(() => {
      console.log('Video merging finished.');
      res.status(200).send('File uploaded and video merged successfully.');
    })
    .catch((err) => {
      console.error('Error:', err);
      res.status(500).send('Error merging videos.');
    });
});

// 视频合并函数
function mergeVideos(segments, output) {
  return new Promise((resolve, reject) => {
    const command = ffmpeg();

    segments.forEach((segment) => {
      command.input(segment);
    });

    command
      .on('end', () => {
        console.log('Video merging finished.');
        resolve();
      })
      .on('error', (err) => {
        console.error('Error:', err);
        reject(err);
      })
      .mergeToFile(output);
  });
}

app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});
